
/*****************静态数据******************/
var taskListModel=[{
	id:1,
	description:'联想官方直营4S店（金源新燕莎MALL）一周岁生日啦！',
	photo_url:'/images/temp/1.jpg',
	timestamp:1466995184261,
	sourceLogo:'http://www.iconpng.com/png/tencentlogo/weixin.png',
	status:'approved',
	is_liked:false,
	likes:1,
	user:{
		id:'1',
		name:'圣骑士',
		profile_image:'/images/avatar1.png'
	}
},{
	id:2,
	description:'第三次水果摊战役',
	photo_url:'/images/temp/2.jpg',
	timestamp:1466995184261,
	sourceLogo:'http://www.iconpng.com/png/tencentlogo/weixin.png',
	status:'approved',
	is_liked:false,
	likes:1,
	user:{
		id:'1',
		name:'菜市场浪人',
		profile_image:'/images/avatar2.png'
	}
},{
	id:3,
	description:'西十楼守城战',
	photo_url:'/images/temp/3.jpg',
	timestamp:1466995184261,
	sourceLogo:'http://www.iconpng.com/png/tencentlogo/weixin.png',
	status:'approved',
	is_liked:false,
	likes:1,
	user:{
		id:'1',
		name:'游侠',
		profile_image:'/images/avatar3.png'
	}
},{
	id:4,
	description:'花鸟鱼虫市场的陷落',
	photo_url:'/images/temp/4.jpg',
	timestamp:1466995184261,
	sourceLogo:'http://www.iconpng.com/png/tencentlogo/weixin.png',
	status:'approved',
	is_liked:false,
	likes:1,
	user:{
		id:'1',
		name:'兽王',
		profile_image:'/images/avatar4.png'
	}
},{
	id:5,
	description:'联想官方直营4S店（金源新燕莎MALL）一周岁生日啦！',
	photo_url:'/images/temp/5.jpg',
	timestamp:1466995184261,
	sourceLogo:'http://www.iconpng.com/png/tencentlogo/weixin.png',
	status:'approved',
	is_liked:false,
	likes:1,
	user:{
		id:'1',
		name:'圣骑士',
		profile_image:'/images/avatar5.png'
	}
},{
	id:6,
	description:'天地批发市场正式宣布与菜市场结盟',
	photo_url:'/images/temp/6.jpg',
	timestamp:1466995184261,
	sourceLogo:'http://www.iconpng.com/png/tencentlogo/weixin.png',
	status:'approved',
	is_liked:false,
	likes:1,
	user:{
		id:'1',
		name:'圣骑士',
		profile_image:'/images/avatar1.png'
	}
},{
	id:7,
	description:'广场舞修道会宣誓效忠居委会',
	photo_url:'/images/temp/7.jpg',
	timestamp:1466995184261,
	sourceLogo:'http://www.iconpng.com/png/tencentlogo/weixin.png',
	status:'approved',
	is_liked:false,
	likes:1,
	user:{
		id:'1',
		name:'圣骑士',
		profile_image:'/images/avatar2.png'
	}
},{
	id:8,
	description:'玉泉路合战战术分析（终极版）',
	photo_url:'/images/temp/8.jpg',
	timestamp:1466995184261,
	sourceLogo:'http://www.iconpng.com/png/tencentlogo/weixin.png',
	status:'approved',
	is_liked:false,
	likes:1,
	user:{
		id:'1',
		name:'圣骑士',
		profile_image:'/images/avatar3.png'
	}
},{
	id:9,
	description:'居委会大使孟主任前往太平路中学进行结盟游说但收效甚微',
	photo_url:'/images/temp/9.jpg',
	timestamp:1466995184261,
	sourceLogo:'http://www.iconpng.com/png/tencentlogo/weixin.png',
	status:'approved',
	is_liked:false,
	likes:1,
	user:{
		id:'1',
		name:'圣骑士',
		profile_image:'/images/avatar4.png'
	}
},{
	id:10,
	description:'菜市场使者老赵宣称若太平路中学加入居委会一方将不再对其手下留情',
	photo_url:'/images/temp/10.jpg',
	timestamp:1466995184261,
	sourceLogo:'http://www.iconpng.com/png/tencentlogo/weixin.png',
	status:'approved',
	is_liked:false,
	likes:1,
	user:{
		id:'1',
		name:'圣骑士',
		profile_image:'/images/avatar5.png'
	}
}];

/*****************backbone 模型******************/

var CollectionList = Backbone.Collection.extend({
	model:function(attrs){
		if(attrs.source=='PC'){
			if(attrs.type=='video'){
				attrs.isVideo=true;
				attrs.poster=attrs.asset_meta_data.poster_image || attrs.photo_url+'?vframe/jpg/offset/1';
			}
			attrs.ratio=attrs.asset_meta_data.ratio
		}
		if(attrs.user){
			attrs.user.profile_image=attrs.user.profile_image || '/dashboard/images/default_profile_image.png'
		}
		return new Backbone.Model(attrs)
	}
});

/*****************react 模块******************/
var Content=React.createClass({
	statusList:[
		{name: i18next.t('material_list.share'),status:'share'},
		{name: i18next.t('material_list.pending') ,status:'pending'},
		{name: i18next.t('material_list.approved'),status:'approved'},
		{name: i18next.t('material_list.refused'),status:'rejected'},
		{name: i18next.t('material_list.deleted'),status:'deleted'}
	],
	getInitialState:function(){
		moment.locale('en', {
		    relativeTime : {
		        past: i18next.t('time.past'),
		        m:  i18next.t('time.minute'),
		        mm: i18next.t('time.minutes'),
		        h:  i18next.t('time.hour'),
		        hh: i18next.t('time.hours'),
		        d:  i18next.t('time.day'),
		        dd: i18next.t('time.days'),
		        M:  i18next.t('time.month'),
		        MM: i18next.t('time.months'),
		        y:  i18next.t('time.year'),
		        yy: i18next.t('time.years')
		    }
		});

		this.collection=new CollectionList();
		this.collection.comparator=this.descSort;
		this.collection.on('all',function(type,item,list){
			this.setState({
				collection:this.collection
			})
		},this);
		
		var status=JSON.parse(localStorage.getItem('photo_list_status') || '{}');

		return {
			collection:this.collection,
			status:status[wallId] || 'pending',
			source:'',
            isDetailOpen: ""
		}
	},
	descSort:function(m1,m2){
		return m2.get('timestamp')-m1.get('timestamp')
	},
	componentDidMount:function(){
		$('#wrapper').unbind('scroll').bind('scroll',function(){
			var scrollTop = $('#wrapper').scrollTop();
			var scrollHeight = $('#wrapper>div').height();
			var windowHeight = $('#wrapper').height();
			
			if(scrollTop + windowHeight>=scrollHeight-50){
				this.loadMore()
			}
		}.bind(this));
		this.loadMore()
	},
	loadMore:function(){
		if(!this.isLoading && !this.complete){
			var collection=this.state.collection,
				last= collection.length ? collection.at(collection.length-1).get('timestamp') : Date.now(),
				status=this.state.status,
				source=this.state.source;

			this.isLoading=true;
			$.ajax({
				url:'/wall/'+wallId+'/photos?count=20&type=old&since='+last+'&status='+status+'&source='+source+'&platform=console',
				dataType:'json',
				success:function(data){
					if(data.success){
						if(data.data.length){
							collection.add(data.data)
						}else{
							//collection.add(taskListModel);
							this.complete=true
						}
					}
					this.isLoading=false
				}.bind(this)
			})
		}
	},
    open: function(id) {
        this.setState({
            isDetailOpen: id
        })
    },
	fixedToolbarList:[
		{
			title: i18next.t('material_list.back_top'),
			icon:'fa-long-arrow-up',
			callback:function(){
				$('#wrapper').animate({scrollTop:0})
			}
		}
	],
	render:function(){
		
		var options=this.props.options,
			socialAccount=options.socialAccount,
			collection=this.state.collection,
            isDetailOpen = this.state.isDetailOpen,
            status=this.state.status,
            statusList=this.statusList;

		return (
			<div>
				<section className="content-header">
					<h1>{i18next.t('material_list.list')}<small>{socialAccount.name}</small><a className="pull-right" href="/console">{i18next.t('material_list.return')}</a></h1>
				</section>
				<div className="content" style={{paddingLeft:'5px',paddingRight:'5px'}}>
					<ListTools content={this} statusList={statusList} />
					{collection.length?<MainList content={this} collection={collection} />:<div className="photolist-empty">
						<i className="fa fa-photo"></i><br></br>
						{i18next.t('material_list.no_has')+_.find(statusList,function(i){return i.status==status}).name.toLowerCase()+i18next.t('material_list.material')}
					</div>}
					{isDetailOpen?<DetailAssets app={this} isDetailOpen={isDetailOpen} data={collection} />:''}
		        </div>
				{this.fixedToolbarList.length?<FixedToolbar itemList={this.fixedToolbarList} />:null}
	        </div>
		)
	}
});

/*右侧浮动按钮组*/
var FixedToolbar=React.createClass({
	render:function(){
		var itemList=this.props.itemList;

		return (
			<div className="fixed-toolbar">
				{itemList.map(function(i){
					return <FixedToolbarItem option={i} />
				})}
			</div>
		)
	}
});

var FixedToolbarItem=React.createClass({
	render:function(){
		var option=this.props.option;

		return (
			<div className="fixed-toolbar-item" title={option.title || ''} onClick={option.callback}>
				<i className={'fa '+(option.icon || 'fa-circle-o')}></i>
			</div>
		)
	}
});

/*图片墙*/
var MainList = React.createClass({
	componentWillMount:function(){
		var self=this,
			timer=null;
		$(window).resize(function(){
			if(timer){clearTimeout(timer)}
			timer=setTimeout(function(){
				self.forceUpdate();
				console.log('resize');
				timer=null
			},500)
		})
	},
	render:function(){
		var content=this.props.content,
			collection=this.props.collection,
			len=collection.length,
			isPhone=$('body').width()<768,
			colNum=$('#main')&&!isPhone?parseInt($('#main').width()/250):1,
			listHtml=[],
			tempArr=[];

			collection.forEach(function(i,index){
				var model=i.toJSON(),
					position=null;

				if(colNum>1&&model.h){
					var col=index<colNum?index:_.indexOf(tempArr,_.min(tempArr)),
						t=tempArr[col] || 0;
					position={
						l:col*250,
						t:t
					}
					tempArr[col]=t+model.h
				}
				listHtml.push(<MainListItem key={i.id} isPhone={isPhone} position={position} model={model} collection={collection} index={index} isAuditing={true} content={content}/>)
			});	

		return (
			<div className="main mainZ-index">
				<div id="main" style={{height:_.max(tempArr)}}>
					{listHtml}
				</div>
			</div>
		)
	}
});

var MainListItem = React.createClass({
	getInitialState:function(){
		var model=_.clone(this.props.model);

		this.refresh();

		return {
			time:(function(){try{return moment(model.timestamp).fromNow()}catch(err){ return i18next.t('time.minute_inside')}})(),
			isLiking:false,
			is_liked:model.is_liked,
			likes:model.likes
		}
	},
	refresh:function(){
		var model=_.clone(this.props.model);

		this.timer=setTimeout(function(){
			if(ReactDOM.findDOMNode()){
				this.setState({
					time:(function(){try{return moment(model.timestamp).fromNow()}catch(err){ return i18next.t('time.minute_inside')}})()
				});
				this.refresh()
			}
		}.bind(this),60000);
	},
	componentWillUnmount:function(){
		clearTimeout(this.timer)
	},
	handle:function(method){
		var content=this.props.content,
			collection=content.state.collection,
			model=this.props.model,
			id=model.id;

		$.ajax({
			type:'post',
			url:'/walls/'+wallId+'/photos/'+id+'/'+method,
			dataType:'json',
			success:function(data){
				console.log(data);
				console.log(id);
				if(data.success && data.data && method != "share"){
					collection.remove(id)
				}
			}
		})
	},
	loaded:function(e){
		var collection=this.props.collection,
			model=this.props.model,
			ele=$(this.refs.item);

		collection.get(model.id).set({
			h:ele.outerHeight(true),
			img_h:e.target.height
		})
	},
    detailMask: function(){
        var data = this.props.collection;
        var model=this.props.model;
        console.log(model.source);
        var open = this.props.content.open;
        open(model.id);
    },
	render:function(){
		var model=this.props.model,
			isAuditing=this.props.isAuditing,
			time=this.state.time,
			likes=this.state.likes,
			position=this.props.position,
			isPhone=this.props.isPhone,
			status=this.props.content.state.status,
			Plan=typeof plan!='undefined'?plan:null,
			allowLike=(Plan && Plan.features) ? Plan.features.allow_like : true,
			contentAudit=(Plan && Plan.features) ? Plan.features.content_audit : true,
			sourceLogo=model.source!='PC'?'/images/icons/'+model.source+'.png':null,
			statistics=model.statistics;
		
		return (
			<div className={model.isVideo?"list_item col-xs-12 list_item_video":"list_item col-xs-12"} style={!isPhone?position?{'position':'absolute','left':position.l,'top':position.t}:{display:'none'}:{}} ref="item">
				<div className="panel panel-default">
					<div className="panel-heading">
						<img className="img-responsive" src={model.isVideo?model.poster:model.photo_url+(isPhone?'?imageView2/4/w/736/imageMogr/auto-orient':'?imageMogr/auto-orient')} onLoad={!model.h?this.loaded:''} style={{width:'100%',height:model.ratio && !isPhone?model.ratio*236:null,backgroundColor:'#ccc'}} />
						{sourceLogo?<img className="source_logo" width="32" height="32" src={sourceLogo} />:null}
						{model.isVideo?<img className="video_icon" src="/images/icons/play.png" />:''}
					</div>
					<div className="panel-body">
						{model.description?<p className = "media media_bottom">{model.description}</p>:null}
                        
						{isAuditing && contentAudit?<div className="text-center">
							<div className="dropdown user user-menu" role="group">
								<a href = "#" className="dropdown-toggle btn-xs text-center" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
									<i className = "glyphicon glyphicon-option-horizontal" style = {{color:'black'}}></i>
								</a>
								<ul className="dropdown-menu">
									<li><a href="#" onClick={this.detailMask}>{i18next.t('material_list.edit')}</a></li>
									<li><a href="#" onClick={function(){this.handle('share')}.bind(this)}>{i18next.t('material_list.share')}</a></li>
								</ul>
							{status!='deleted'?<a href="#" className=" btn-xs text-center " onClick={function(){this.handle('delete')}.bind(this)} title= {i18next.t('material_list.delete')}><i className="glyphicon glyphicon-trash" style = {{color:'black'}}></i></a>:null}
							{status!='approved'?<a href="#" className=" btn-xs text-center " onClick={function(){this.handle('approve')}.bind(this)} title= {i18next.t('material_list.pass')}><i className="glyphicon glyphicon-ok" style = {{color:'green'}}></i></a>:null}
							{status!='rejected'?<a href="#" className=" btn-xs text-center " onClick={function(){this.handle('reject')}.bind(this)} title= {i18next.t('material_list.refuses')}><i className="glyphicon glyphicon-remove" style = {{color:'red'}}></i></a>:null}
						</div></div>:null}
						<div className="clearfix"></div>
						<div className="media media_auditing">
							<a href="javascript:void(0)" className="media-left"><img className="img-circle avatar" src={model.user.profile_image} /></a>
							<div className="media-body text-muted">{model.user.name}<br /><span className="create-time">{time}</span></div>
							{allowLike?<span className="media-right text-right text-muted like" nowrap="nowrap" >
								<i className="glyphicon glyphicon-thumbs-up"></i>{likes || 0}
							</span>:''}
						</div>
						{statistics?<div className="media media_auditing">
							<div>{i18next.t('material_list.click')} : {statistics.clicks}</div>
							<div>{i18next.t('material_list.like')} : {statistics.likes}</div>
							<div>{i18next.t('material_list.transform')} : {statistics.conversions}</div>
						</div>:null}
						
					</div>
				</div>
			</div>
		)
	}
});

//anxu  mask
var DetailAssets = React.createClass({
    getInitialState: function(){
        var model = this.props.data.get(this.props.isDetailOpen).toJSON();
        return {
            additional_url: model.additional_url,
            description: model.description,
            tag: model.tag,
			update_all_links:false
        }
    },
    close: function(){
        var cancle = this.props.app.open;
        cancle(null);
    },
	inputValue:function(e){
		var state={},
			key=e.target.name,
			val=e.target.value;

		state[key]=val;

		this.setState(state)
	},
	submit:function(){
		var self = this,
			id = this.props.isDetailOpen,
			model = this.props.data.get(id),
			state = this.state;

		$.ajax({
			type:'post',
			url:'/walls/' + wallId + '/assets/' +id,
			data:{
				asset_id:id,
				description:state.description,
				additional_url:state.additional_url,
				update_all_links:state.update_all_links,
				tag:state.tag
			},
			dataType:'json',
			success:function(data){
				if(data){
					model.set({
						description:state.description,
						additional_url:state.additional_url,
						tag:state.tag
					})
					self.close()
				}
			},
			error:function(){

			}
		})
	},
    render: function(){
        var id = this.props.isDetailOpen;
        var collection = this.props.data;
        var description = this.state.description;
        var additional_url = this.state.additional_url;
        var tag = this.state.tag;
		var update_all_links = this.state.update_all_links;
		var model = collection.get(id).toJSON();
        var src = model.photo_url,
			type = model.type;
        /*collection.forEach(function(item, index){
            var data= item.toJSON();
            
            if(id == data.id){
                if(data.type == "video"){
                    src = data.poster;
                } else {
                    src = data.photo_url;
                }
            }
        });*/
        return (
            <div>
                <div className={id? "modal fade in" : "fade"} style={{display:id?"block" : "none"}}   role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
                    <div className="modal-dialog modal-lg modalLg">
                        <div className="modal-content">
                            <div className="modal-header">
                            	<button type="button" className="close">
									<span onClick={this.close}>&times;</span>
									<span className="sr-only">Close</span>
								</button>
                                <h4 className="modal-title">{i18next.t('material_list.material_details')}</h4>
                            </div>
                            <form method="POST"  action={'/walls/' + wallId + '/assets/' +id}>
                                <div className="modal-body fix-body">
                                    <div className="col-xs-8 asset-image">
                                        {type=='video'?<div className="divVideo">
											<video className="videClass" src={src} controls="controls" autoPlay="autoplay"></video>
										</div>:<img className="fixed-image" src={src} />}
                                    </div>
                                    <div className="col-xs-4 well">
                                        <input type="hidden" name="asset_id" value={id} />
                                        <div className="form-group">
                                        	<label>{i18next.t('material_list.material_description_text')}</label>
                                        	<textarea rows="4" style={{resize:'none'}} onChange={this.inputValue} name="description" value={description} className="form-control" placeholder= {i18next.t('material_list.description')}></textarea>
                                        	<p className="help-block">{i18next.t('material_list.text')}</p>
                                        </div>
                                        <div className="form-group">
                                        	<label>{i18next.t('material_list.url')}</label>
                                        	<input type="text" onChange={this.inputValue} name="additional_url" value={additional_url} className="form-control" placeholder= {i18next.t('material_list.address')} />
                                        	<p className="help-block">{i18next.t('material_list.jump_url')}</p>
                                        	<div className="checkbox" style={{display:'none'}}>
												<label>
													<input name="update_all_links" value={update_all_links} onChange={this.inputValue} type="checkbox" /> {i18next.t('material_list.ismaterial')}
												</label>
											</div>
                                        </div>
                                        <div className="form-group">
                                        	<label>{i18next.t('material_list.picture_tag')}</label>
                                        	<input type="text" onChange={this.inputValue} name="tag" value={tag} className="form-control" placeholder= {i18next.t('material_list.lable')}/>
                                        	<p className="help-block">{i18next.t('material_list.groupby')}</p>
                                        </div>
                                    </div>
                                </div>
                                <div className="modal-footer">
                                    <button type="button" className="btn btn-default" data-dismiss="modal" onClick={this.close}>{i18next.t('material_list.cancel')}</button>
                                    <button type="button" className="btn btn-primary" onClick={this.submit}>{i18next.t('material_list.save')}</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        )
    }
});

var ListTools = React.createClass({
	getInitialState : function(){
		return {
			isOpen : false
		}
	},
	changeStatus:function(status){
		var content=this.props.content,
			statusCache=JSON.parse(localStorage.getItem('photo_list_status') || '{}');

		if(status!=content.state.status){
			content.setState({
				status:status
			});
			content.collection.reset();
			setTimeout(function(){
				content.complete=false;
				content.loadMore()
			},0)
		}

		statusCache[wallId]=status;
		localStorage.setItem('photo_list_status',JSON.stringify(statusCache))
	},
	changeSource:function(e){
		var content=this.props.content,
			source=e.target.value;
		
		if(source!=content.state.source){
			content.setState({
				source:source
			});
			content.collection.reset();
			setTimeout(function(){
				content.complete=false;
				content.loadMore()
			},0)
		}
	},
	open:function(){
		this.setState({
			isOpen:true
		})
	},
	render:function(){
		var self=this,
			content=this.props.content,
			statusList=this.props.statusList,
			status=content.state.status,
			isOpen=this.state.isOpen;

		return (
			<div className="box-header">
				<div className="form-group pull-right" style={{marginLeft:'10px'}}>
					<select className="form-control" onChange={this.changeSource}>
						<option value="">{i18next.t('material_list.all_sources')}</option>
						<option value="wechat">{i18next.t('material_list.wechat')}</option>
						<option value="PC">{i18next.t('material_list.admin')}</option>
						<option value="dianping"  style={{display:'none'}}>{i18next.t('material_list.dianping')}</option>
					</select>
				</div>
				<div className="btn-group pull-right">
					{statusList.map(function(i){
						return <div className = "pull-left"><div key={i.status}  className={status==i.status?"btn btn-active":"btn btn-default"} onClick={function(){self.changeStatus(i.status)}.bind(self)}>{i.name}</div></div>
					})}
				</div>
				<button type="button" className="btn btn-default btn-lg btnnStyle" data-toggle="modal"  onClick={this.open}>
					{i18next.t('material_list.upload_material')}
				</button>
				{isOpen?<UploadMaterial media = {this} content={content}/>:null}
			</div>
		)
	}
});
/*上传素材*****/
var UploadMaterial = React.createClass({
	mixins:[UploadCDN()],
	getInitialState : function(){
		return {
			Proportion : null,
			mediaType : null,
			src : null,
			isLoading:false,
			media:null,
			message:null,
			mediaTypeDetail:null,
			description:''
		};
	},
	supportType : ['jpg','jpeg','png','gif','mp4','3gp'],
	UpLoad : function(e){
		var self = this,
			type = e.target.files[0].type.split('/'),
			mediaType = type[0]=='image'?'photo':type[0],
			supportType = this.supportType,
			isTypeValid=this.validFileType(type[1],supportType);
		
		
		this.setState({
			mediaType:mediaType,
			mediaTypeDetail:type[1]
		},function(){
			if(isTypeValid){
				if(type[0]=='video'){
					var file=e.target.files[0];
					var url = (window.URL) ? window.URL.createObjectURL(file) : window.webkitURL.createObjectURL(file);
					self.setState({
						src : url,
						media : e.target.files[0]
					})
				}else if(type[0]=='image'){
					var reader=new FileReader();
					reader.onload=function(){
						self.setState({
							src : this.result,
							media : e.target.files[0]
						})
					};
					reader.readAsDataURL(e.target.files[0])
				}
			}else{
				self.setState({
					errorList:[{
						info: i18next.t('material_list.format')+supportType.join('、')+i18next.t('material_list.type'),
						target:mediaType
					}],
					message:null
				})
			}
		})
		
	},
	open : function(){
		var media=this.props.media,
			isOpen=media.state.isOpen;

		media.setState({
			isOpen : !isOpen
		})
	},
	getRatio : function(e,type){
		var self = this,
			isVideo=type=='video',
			width = isVideo?e.target.videoWidth:e.target.width,
			height = isVideo?e.target.videoHeight:e.target.height;
		self.setState({
			Proportion : (height/width).toFixed(2),
			width:width,
			height:height
		})
	},
	addLoading:function(){
		this.setState({
			isLoading:true
		})
	},
	removeLoading:function(state){
		this.setState(_.extend({
			isLoading:false
		},state))
	},
	submit:function(){
		var self=this,
			media=this.props.media,
			content=this.props.content,
			state=this.state,
			dataBody={
				message : state.description,
				ratio : state.Proportion,
				width : state.width,
				height : state.height,
				assetType : state.mediaType
			};

		if(this.isValid()){
			this.addLoading();

			if(state.key){
				submitAll(state.key)
			}else{
				this.getUploadParam(state.mediaTypeDetail,function(uploadParam){
					if(uploadParam){
						self.uploadCDN(state.media,uploadParam,function(){
							self.setState({
								key:uploadParam.key
							});
							submitAll(uploadParam.key)
						})
					}else{
						self.removeLoading({
							success:false,
							message: i18next.t('material_list.upload_failed')
						})
					}
				})
			}
		}
		
		function submitAll(image_key){
			dataBody.url = image_key;
			$.ajax({
				type:'post',
				url:'/wall/'+wallId+'/photos/',
				data:dataBody,
				dataType:'json',
				success:function(data){
					if(data.data){
						media.changeStatus('approved');
						content.state.collection.add([data.data]);
						self.open()
					}else{
						self.removeLoading({
							message:{
								success:false,
								message:data.error
							}
						});
					}
				},
				error:function(){
					self.removeLoading({
						message:{
							success:false,
							message: i18next.t('material_list.upload_failed')
						}
					})
				}
			})
		}
		
	},
	isValid:function(e){
		var state = this.state,
			err = [],
			key = e ? e.target ? e.target.name : e : null,
			supportType = this.supportType,
			isTypeValid=this.validFileType(state.mediaTypeDetail,supportType);

		if(!state.media || !state.mediaType){
			err.push({
				info: i18next.t('material_list.error_message'),
				target:state.mediaType
			})
		}else if(!isTypeValid){
			err.push({
				info: i18next.t('material_list.format')+supportType.join('、')+i18next.t('material_list.type'),
				target:state.mediaType
			})
		}

		

		if(err.length){
			if(key){
				err=_.filter(err,function(i){
					return i.target==key
				})
			}

			this.setState({
				errorList:err,
				message:null
			});
			return false
		}else{
			this.setState({
				errorList:[],
				message:null
			});
			return true
		}
	},
	renderErrorInfo:function(key){
		var state=this.state,
			errorList=_.groupBy(state.errorList,'target'),
			error=errorList[key];

		if(error){
			return _.map(error,function(i){
				return <span className="help-block">{i.info}</span>
			})
		}else{
			return ''
		}
	},
	inputValue:function(e){
		var state={},
			key=e.target.name,
			val=e.target.value;

		state[key]=val;

		this.setState(state)
	},
	render : function(){
		var self=this,
			state=this.state,
			mediaType = this.state.mediaType,
			src = this.state.src,
			mediaHtml=<div><h1 className="jubo">{i18next.t('material_list.click_upload_material')}!</h1><h3 className="HMargin">{i18next.t('material_list.support_video')}<b>MP4</b>{i18next.t('material_list.picture')}</h3></div>

		if(mediaType && src){
			switch (mediaType){
				case 'photo':
					mediaHtml=<img className="imageClass" src={src} onLoad={function(e){self.getRatio(e,'image')}}/>;
					break;
				case 'video':
					mediaHtml=<div className="divVideo"><video className="videClass" src={src} controls="controls" autoPlay="autoplay" onCanPlay={function(e){self.getRatio(e,'video')}}></video></div>;
					break;
				default:
					mediaHtml=<div><h1 className="jubo">{i18next.t('material_list.click_upload_material')}!</h1><h3 className="HMargin">{i18next.t('material_list.support_video')}<b>MP4</b>{i18next.t('material_list.picture')}</h3></div>
			}
		}

		return (
			<div>
				<div className="modal fade in" style={{display:'block'}}   role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
					<div className="modal-dialog modal-lg modalLg">
						<div className="modal-content">
							<div className="modal-header">
								<button type="button" className="close" data-dismiss="modal">
									<span aria-hidden="true" onClick={this.open}>&times;</span>
									<span className="sr-only">Close</span></button>
								<h4 className="modal-title" id="myModalLabel">{i18next.t('material_list.upload_material')}</h4>
							</div>


							
							<div className="modal-body">
								<div className={this.renderErrorInfo(mediaType)?"form-group has-error":"form-group"} >
									<label htmlFor="upload_avatar" className="LableWH">
										<input className="inputZIndex" name={mediaType}  id="upload_avatar" type="file" onChange={this.UpLoad} onBlur={this.isValid} required/>
										<div className="imgDivStyle">
											<div className="imgPosition">
												<div className="jumbotron jumbotronStyle pull-left">
													{mediaHtml}
												</div>
											</div>
										</div>
									</label>
									<div className="text-center">{this.renderErrorInfo(mediaType)}</div>
								</div>
								<div className="textareaDivStyle">
									<textarea name="description" style={{resize:'none'}} onChange={this.inputValue} className="form-control formCortorlText" rows="4" placeholder= {i18next.t('material_list.placeholder')} value={state.description}></textarea>
								</div>
								{state.message?<div className={state.message.success?"form-group has-success":"form-group has-error"}>
									<p className="help-block text-right">{state.message.message}</p>
								</div>:null}
							</div>
							<div className="modal-footer">
								<button type="button" className="btn btn-default" data-dismiss="modal" onClick={this.open}>{i18next.t('material_list.close')}</button>
								<button type="submit" className={"btn "+(state.isLoading?"btn-default":"btn-primary")} onClick={this.submit}>{state.isLoading? i18next.t('material_list.saveing'):i18next.t('material_list.save')}</button>
							</div>
							<input type="hidden" name="proportion" value={state.Proportion} required />
							
						</div>
					</div>
				</div>
			</div>
		)
	}
});

